package com.smartleanx.module.hrm.service.esign.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.smartleanx.module.hrm.dal.mysql.esign.HrmETempFileMapper;
import com.smartleanx.module.hrm.service.esign.service.HrmEFileService;
import com.smartleanx.module.hrm.service.esign.service.HrmETempFileService;
import com.smartleanx.module.hrm.service.esign.temp.po.HrmEFile;
import com.smartleanx.module.hrm.service.esign.temp.po.HrmETempFile;
import com.smartleanx.module.hrm.util.esign.FileUtil;
import com.smartleanx.module.hrm.util.esign.exception.EsignDemoException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * e签宝模板和底稿文件Service实现
 *
 * @author xzq
 * @since 2025-07-07 16:47:28
 */
@Service
public class HrmETempFileServiceImpl extends ServiceImpl<HrmETempFileMapper, HrmETempFile> implements HrmETempFileService {
    @Autowired
    private HrmEFileService hrmEFileService;

    @Override
    public int saveList(List<Long> fileIds, Long tempId,String type) {
        List<HrmETempFile> collect = fileIds.stream().map(p -> {
            HrmETempFile hrmETempFile = new HrmETempFile();
            hrmETempFile.setDataStatus(1);
            hrmETempFile.setFileId(p);
            hrmETempFile.setTempId(tempId);
            hrmETempFile.setType(Integer.parseInt(type));
            HrmEFile file = hrmEFileService.getById(p);
            try {
                if(StrUtil.isBlank(file.getEFileId())){
                    String fileId = FileUtil.fileHTML(file.getFileUrl());
                    hrmETempFile.setEFileId(fileId);
                }
            } catch (EsignDemoException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return hrmETempFile;
        }).collect(Collectors.toList());

        saveBatch(collect);

        return collect.size();
    }

    @Override
    public List<HrmEFile> getFileListByTempId(Long tempId) {
        List<HrmETempFile> tempFileList = list(new LambdaQueryWrapper<HrmETempFile>()
                .eq(HrmETempFile::getDataStatus, 1)
                .eq(HrmETempFile::getTempId, tempId));

        List<Long> fileIds = tempFileList.stream().map(HrmETempFile::getFileId).collect(Collectors.toList());
        return hrmEFileService.getFileByFileIds(fileIds);
    }

    @Override
    public boolean removeTempFileByTempId(Long tempId) {
        return update(new LambdaUpdateWrapper<HrmETempFile>()
        .eq(HrmETempFile::getDataStatus,1)
        .eq(HrmETempFile::getTempId,tempId)
        .set(HrmETempFile::getDataStatus,0));
    }
}
